package pe.gob.onpe.facade;

import java.util.List;
import java.util.logging.Level;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import pe.gob.onpe.ejb.LogUtil;
import pe.gob.onpe.ejb.RegistroLinea;
import pe.gob.onpe.ejb.id.RegistroLineaId;
import pe.gob.onpe.facade.local.RegistroLineaFacadeLocal;
import pe.gob.onpe.facade.remote.RegistroLineaFacadeRemote;


/**
 * Facade for entity RegistroLinea.
 * 
 * @see pe.gob.onpe.ejb.RegistroLinea
 * @author MyEclipse Persistence Tools
 */
@Stateless
public class RegistroLineaFacade implements RegistroLineaFacadeLocal,
		RegistroLineaFacadeRemote {
	// property constants
	public static final String DIRECCION = "direccion";
	public static final String CORREOELECTRONICO = "correoelectronico";
	public static final String NUMERONIP = "numeronip";
	public static final String NUMEROINTENTOVOTACION = "numerointentovotacion";
	public static final String EMITIOVOTO = "emitiovoto";
	public static final String CONTRASENA = "contrasena";
	public static final String ESTADOINSCRIPCION = "estadoinscripcion";

	@PersistenceContext
	private EntityManager entityManager;

	/**
	 * Perform an initial save of a previously unsaved RegistroLinea entity. All
	 * subsequent persist actions of this entity should use the #update()
	 * method.
	 * 
	 * @param entity
	 *            RegistroLinea entity to persist
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void save(RegistroLinea entity) {
		LogUtil.log("saving RegistroLinea instance", Level.INFO, null);
		try {
			entityManager.persist(entity);
			LogUtil.log("save successful", Level.INFO, null);
		} catch (RuntimeException re) {
			LogUtil.log("save failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Delete a persistent RegistroLinea entity.
	 * 
	 * @param entity
	 *            RegistroLinea entity to delete
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void delete(RegistroLinea entity) {
		LogUtil.log("deleting RegistroLinea instance", Level.INFO, null);
		try {
			entity = entityManager.getReference(RegistroLinea.class, entity
					.getId());
			entityManager.remove(entity);
			LogUtil.log("delete successful", Level.INFO, null);
		} catch (RuntimeException re) {
			LogUtil.log("delete failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Persist a previously saved RegistroLinea entity and return it or a copy
	 * of it to the sender. A copy of the RegistroLinea entity parameter is
	 * returned when the JPA persistence mechanism has not previously been
	 * tracking the updated entity.
	 * 
	 * @param entity
	 *            RegistroLinea entity to update
	 * @returns RegistroLinea the persisted RegistroLinea entity instance, may
	 *          not be the same
	 * @throws RuntimeException
	 *             if the operation fails
	 */
	public RegistroLinea update(RegistroLinea entity) {
		LogUtil.log("updating RegistroLinea instance", Level.INFO, null);
		try {
			RegistroLinea result = entityManager.merge(entity);
			//entityManager.flush();
			LogUtil.log("update successful", Level.INFO, null);
			return result;
		} catch (RuntimeException re) {
			LogUtil.log("update failed", Level.SEVERE, re);
			throw re;
		}
	}

	public RegistroLinea findById(RegistroLineaId id) {
		LogUtil.log("finding RegistroLinea instance with id: " + id,
				Level.INFO, null);
		try {
			RegistroLinea instance = entityManager
					.find(RegistroLinea.class, id);
			return instance;
		} catch (RuntimeException re) {
			LogUtil.log("find failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Find all RegistroLinea entities with a specific property value.
	 * 
	 * @param propertyName
	 *            the name of the RegistroLinea property to query
	 * @param value
	 *            the property value to match
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            number of results to return.
	 * @return List<RegistroLinea> found by query
	 */
	@SuppressWarnings("unchecked")
	public List<RegistroLinea> findByProperty(String propertyName,
			final Object value, final int... rowStartIdxAndCount) {
		LogUtil.log("finding RegistroLinea instance with property: "
				+ propertyName + ", value: " + value, Level.INFO, null);
		try {
			final String queryString = "select model from RegistroLinea model where model."
					+ propertyName + "= :propertyValue";
			Query query = entityManager.createQuery(queryString);
			query.setParameter("propertyValue", value);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			LogUtil.log("find by property name failed", Level.SEVERE, re);
			throw re;
		}
	}

	public List<RegistroLinea> findByDireccion(Object direccion,
			int... rowStartIdxAndCount) {
		return findByProperty(DIRECCION, direccion, rowStartIdxAndCount);
	}

	public List<RegistroLinea> findByCorreoelectronico(
			Object correoelectronico, int... rowStartIdxAndCount) {
		return findByProperty(CORREOELECTRONICO, correoelectronico,
				rowStartIdxAndCount);
	}

	public List<RegistroLinea> findByNumeronip(Object numeronip,
			int... rowStartIdxAndCount) {
		return findByProperty(NUMERONIP, numeronip, rowStartIdxAndCount);
	}

	public List<RegistroLinea> findByNumerointentovotacion(
			Object numerointentovotacion, int... rowStartIdxAndCount) {
		return findByProperty(NUMEROINTENTOVOTACION, numerointentovotacion,
				rowStartIdxAndCount);
	}

	public List<RegistroLinea> findByEmitiovoto(Object emitiovoto,
			int... rowStartIdxAndCount) {
		return findByProperty(EMITIOVOTO, emitiovoto, rowStartIdxAndCount);
	}

	public List<RegistroLinea> findByContrasena(Object contrasena,
			int... rowStartIdxAndCount) {
		return findByProperty(CONTRASENA, contrasena, rowStartIdxAndCount);
	}

	public List<RegistroLinea> findByEstadoinscripcion(
			Object estadoinscripcion, int... rowStartIdxAndCount) {
		return findByProperty(ESTADOINSCRIPCION, estadoinscripcion,
				rowStartIdxAndCount);
	}

	/**
	 * Find all RegistroLinea entities.
	 * 
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            count of results to return.
	 * @return List<RegistroLinea> all RegistroLinea entities
	 */
	@SuppressWarnings("unchecked")
	public List<RegistroLinea> findAll(final int... rowStartIdxAndCount) {
		LogUtil.log("finding all RegistroLinea instances", Level.INFO, null);
		try {
			final String queryString = "select model from RegistroLinea model";
			Query query = entityManager.createQuery(queryString);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			LogUtil.log("find all failed", Level.SEVERE, re);
			throw re;
		}
	}

	public Long totalCiudadanosVotaron(Long procesoElectoralId) {
		String consulta = "SELECT COUNT(*) FROM RegistroLinea u WHERE u.id.procesoElectoralId = :procesoElectoralId and u.emitiovoto=1 ";
		Query query = entityManager.createQuery(consulta);
		query.setParameter("procesoElectoralId", procesoElectoralId);
		Long cantidad =  (Long) query.getSingleResult();
		return cantidad;
	}

}